package com.sunny.dislock;

import redis.clients.jedis.Jedis;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Author zsunny
 * @Date 2018/9/12 15:44
 * @Mail zsunny@yeah.net
 */
public class DisLock {

    private static final String DEFAULT_HOST = "222.201.145.179";
    private static final int DEFAULT_PORT = 5056;
    private Jedis jedis;

    public DisLock(String host, int port) {
        jedis = new Jedis(host, port);
    }

    public boolean tryLock() throws UnknownHostException {
        long res = jedis.setnx("lock",getName());
        jedis.expire("lock", 20);
        if(1 == res){
            return true;
        }
        return false;
    }

    public String getName() throws UnknownHostException {
        InetAddress inetAddress = InetAddress.getLocalHost();
        String name = inetAddress.getHostName();
        String threadName = Thread.currentThread().getName();
        return name+" "+threadName;
    }

    public static void main(String[] args) {

        DisLock disLock = new DisLock(DEFAULT_HOST, DEFAULT_PORT);


        new Thread(()->{
            try {
                System.out.println(disLock.tryLock());
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }).start();
//        try {
//            System.out.println(disLock.tryLock());
//        } catch (UnknownHostException e) {
//            e.printStackTrace();
//        }

    }
}
